package com.config;

import com.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private JWTUtil jwtUtil;

    @Value("${web.cors}")
    private String [] cors;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        System.out.println("注册CorsMappings");
/*        registry.addMapping("/**")  // 允许所有路径
                .allowedOrigins("http://localhost:9527", "http://localhost:8080","http://localhost:8081")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")  // 允许的请求方法
                .allowedHeaders("Content-Type", "Authorization", "*")  // 允许的请求头
                .allowCredentials(true);  // 允许带上认证信息（如 token）*/

        /*registry.addMapping("/**")
                .allowedOrigins("http://localhost:9527",
                        "http://localhost:8080",
                        "http://localhost:8081",
                        "http://owninfo.zone.id:8938",
                        "https://owninfo.zone.id",
                        "http://111.173.104.162:8938")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("Content-Type", "Authorization","*")  // 显式列出需要的头部  *的内容有token  tokenuserid
                .allowCredentials(true);*/
        System.out.println(cors[0]);
        registry.addMapping("/**")
                .allowedOrigins(cors)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("Content-Type", "Authorization","*")  // 显式列出需要的头部  *的内容有token  tokenuserid
                .allowCredentials(true);
        System.out.println(registry);
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("注册拦截器");
        // 注册自定义拦截器
        registry.addInterceptor(new TokenInterceptor(jwtUtil))
                .addPathPatterns("/api/**") ; // 设置拦截的 URL 模式
                //.excludePathPatterns("/api/public/*");  // 排除不需要拦截的路径
    }
}